import type { BaseResponse } from "@/api/response";
import type { BaseResource, MergePathReq } from "../k8s";
import { computed, onMounted, reactive, ref } from "vue";
import { useVerifyRouter } from "@/router/use";
import { objectToYaml } from "../../utils";

type ResourceDetailsReq<T extends BaseResource> = {
  getDetailsReq: (req: MergePathReq, data?: T) => BaseResponse<T>;
};

export const useBaseDetailsProvider = <T extends BaseResource>(
  request: ResourceDetailsReq<T>,
  autoReload?: boolean
) => {
  // 详情对象
  const detailsModel = ref<T>();
  const _yamlDetails = ref<string>();
  const yamlDetailsModel = computed({
    get() {
      if (!_yamlDetails.value) {
        _yamlDetails.value = objectToYaml(detailsModel.value ?? {});
      }
      return _yamlDetails.value;
    },
    set(value) {
      _yamlDetails.value = value;
    }
  });

  // ui状态
  const uiState = reactive({
    loading: false
  });

  // 检索条件
  const query = reactive({
    cluster: "",
    namespace: "",
    name: "",
    yaml: false
  });

  const router = useVerifyRouter();

  const reloadDetails = async () => {
    uiState.loading = true;
    return request
      .getDetailsReq({
        cluster: query.cluster,
        namespace: query.namespace,
        srcName: query.name
      })
      .then(data => {
        if (data) {
          detailsModel.value = data;
        }
      })
      .catch(e => {
        console.error(e);
      })
      .finally(() => {
        uiState.loading = false;
      });
  };

  const reloadQuery = async () => {
    const { cluster, namespace, name, yaml, yamlShow } = router.query;
    cluster && (query.cluster = `${cluster}`);
    namespace && (query.namespace = `${namespace}`);
    name && (query.name = `${name}`);
    if ((yaml && yaml === "true") || (yamlShow && yamlShow === "true")) {
      query.yaml = true;
    }
    return reloadDetails();
  };

  if (autoReload) {
    onMounted(reloadQuery);
  }

  const toggleYaml = () => {
    query.yaml = !query.yaml;
  };

  return {
    yamlDetailsModel,
    toggleYaml,
    detailsModel,
    uiState,
    query,
    router,
    reloadDetails,
    reloadQuery
  };
};
